package com.neusoft.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.neusoft.common.CommonReslut;
import com.neusoft.entity.Admin;
//import com.neusoft.entity.Course;
import com.neusoft.excelUtils.ExcelForList;
import com.neusoft.service.AdminService;
//import com.neusoft.service.CourseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * (Admin)表控制层
 *
 * @author makejava
 * @since 2020-05-26 19:14:25
 */
@Controller
@RequestMapping("admin")
public class AdminController {
    /**
     * 加入日志的使用，减少使用sout打印debug
     */
    private Logger logger=LoggerFactory.getLogger(getClass());
    /**
     * 服务对象
     */
    @Resource
    private AdminService adminService;

//    @Autowired
//    private CourseService courseService;

    //admin页面的查询所有功能
    @PostMapping("queryAll")
    @ResponseBody
    public Object queryAll(@RequestParam("page") Integer page, @RequestParam("limit")Integer limit, @RequestBody Admin admin){
        CommonReslut<Admin> result=new CommonReslut<>();
        IPage<Admin> iPage =adminService.queryAllByLimit(page,limit,admin);
        result.setCode(0);
//        System.out.println("iPage.getTotal():::"+iPage.getTotal());
        result.setCount(iPage.getTotal());
        result.setData(iPage.getRecords());
        return result;
    }
    //登录界面
    @RequestMapping("tologin")
    public String tologin(){
        return  "login";
    }

    //首页
    @RequestMapping("towelcome")
    public String towelcome(){
        return  "welcome";
    }

    @GetMapping("selectOne")
    public Admin selectOne(Integer id) {
        return this.adminService.queryById(id);
    }

    //管理查询界面
    @RequestMapping("tolist")
    public String tolist() {
        return "/user/table";
    }
    //管理添加界面
    @RequestMapping("toadd")
    public String toadd(Model model) {
        model.addAttribute("admin",new Admin());
        return "/user/admin_add";
    }
      //管理添加保存功能
    @PostMapping("save")
    @ResponseBody
    public Object save(@RequestBody Admin admin) {
        boolean result=false;

        if(admin.getId()!=null){
            //编辑
            result =adminService.update(admin)>0;
        }else{
            //添加
            result=adminService.insert(admin).getId()!=null;
        }


        return result;
    }
      //管理更新功能
    @RequestMapping("toedit")
    public String toedit(int id,Model model) {

        System.out.println("id:::"+id);
        Admin admin=adminService.queryById(id);
        model.addAttribute("admin",admin);

        return "user/admin_add";
    }
      //管理删除功能
    @PostMapping("delete")
    @ResponseBody
    public boolean delete(@RequestParam("ids") Integer[] ids) {

        if(ids==null ||ids.length==0)
            return false;
//        System.out.println(ids[0]);
//        return true;

        return adminService.deleteById(Arrays.asList(ids));
    }


    //上传
//    @PostMapping(value="upload")
//    @ResponseBody
//    public  Object imporCourse(MultipartFile file, HttpSession httpSession) throws IOException {
//        CommonReslut<String> result = new CommonReslut<>();
//        InputStream in = file.getInputStream();
//        String fileOriginalName = file.getOriginalFilename();
//        String fileName = file.getName();
//        String excelType = fileOriginalName.substring(fileOriginalName.indexOf(".") + 1);
//
//        //记录插入多条记录到了数据库；
//        int importSuccessNum = 0;
//        int importAllNum = 0;
//        boolean importSuccess;
//
//        System.out.println("in:::" + in);
//        System.out.println("fileOriginalName:::" + fileOriginalName);
//        System.out.println("fileName:::" + fileName);
//        System.out.println("excelType:::" + excelType);
//        List<Object> forlist = ExcelForList.ExcelForList(file, Course.class, true, excelType);
//        for (Object object : forlist) {
//            Course course = (Course) object;
//            importAllNum++;
//            importSuccess = courseService.importExcel(course);
//            if (importSuccess)
//                importSuccessNum++;
//
//        }
//        httpSession.setAttribute("importAllNum", importAllNum);
//        httpSession.setAttribute("importSuccessNum", importSuccessNum);
//
//        if (importSuccessNum <= 0)
//            result.setMsg("上传excel文件出错！");
////            return "success!"+"应处理"+importAllNum+"条,已成功处理"+importSuccessNum+"条！";
//
//        result.setData(file.getOriginalFilename());
//        return result;
//
//    }
    //登录功能验证
    @GetMapping("login")
    public String login(String account, String password, String captcha, Model model,HttpServletResponse response) {
//        Cookie account_cookie = new Cookie("account", account);
//        Cookie password_cookie = new Cookie("password", password);
//        httpSession.setAttribute("account",account);
//        httpSession.setAttribute("password",password);
        // 输出到客户端
//        response.addCookie(account_cookie);
//        response.addCookie(password_cookie);

        logger.info(account);
        logger.info(password);
        logger.info("Start to verify acount [{}]",account);
        logger.info("Start to verify password [{}]",password);
        logger.trace("最低级别");
        logger.debug("第二");
        logger.info("第三");
        logger.warn("第四");
        logger.error("第五");

        // 新建Cookie
        Cookie account_cookie = new Cookie("account", account);
        Cookie password_cookie = new Cookie("password", password);
        // 输出到客户端
        response.addCookie(account_cookie);
        response.addCookie(password_cookie);
        model.addAttribute("account",account);
        if(this.adminService.login(account,password)!=null&&captcha.equals("xszg"))
            return "index";
        return "OK";
    }

    @RequestMapping(value = "checkCookie")
    public String checkCookie(String account, String password, HttpServletResponse response){
        // 新建Cookie
        Cookie account_cookie = new Cookie("account", account);
        Cookie password_cookie = new Cookie("password", password);
        // 输出到客户端
        response.addCookie(account_cookie);
        response.addCookie(password_cookie);
        return "redirect:tologin";
    }
//    @RequestMapping(value = "test")
//    public String test(@Param("id") int id,@Param("name") String name){
//
//        return "{id:"+id+",name:"+name+"}";
//    }



//    @RequestMapping(value = "getCookie")
//    public String getCookie(@CookieValue("account") String account, @CookieValue("password") String password){
//        // 控制台输出
//        System.out.println("account: " + account);
//        System.out.println("password: " + password);
//        return "OK";
//    }

}